<template>
    <!-- 分享海报canvas - 默认隐藏 -->
    <canvas canvas-id="shareCanvas" id="shareCanvas"
        style="width: 300px; height: 400px; position: fixed; left: -9999px;"></canvas>
</template>

<script setup lang="ts">
import { ref, computed, getCurrentInstance } from "vue";
import { useToast } from "wot-design-uni";
import { useUserStore } from "@/store/modules/user";
import { useThemeStore } from "@/store/modules/theme";
import QRCode from 'qrcode';

const toast = useToast();
const userStore = useUserStore();
const themeStore = useThemeStore();
const userInfo = computed(() => userStore.userInfo);
const defaultAvatar = "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250926/aab14ee17a5240fca6afb57789e74445.png";
// 获取当前组件实例，用于小程序环境下的selectorQuery
const instance = getCurrentInstance();

// 生成分享海报
const createProductSharePoster = async () => {
    try {
        // 显示加载提示
        uni.showLoading({
            title: '生成海报中...',
        });

        // 获取用户信息
        const userId = userInfo.value?.userId;
        const nickname = userInfo.value?.nickname || '匿名用户';
        const avatar = userInfo.value?.avatar || defaultAvatar;
        // 生成分享链接
        // 适配H5和小程序环境的链接生成
        let shareUrl = '';

        if (typeof window !== 'undefined') {
          // H5环境
          shareUrl = `${window.location.origin}/#/pages/login/wechat-authorize?userId=${userId || 'unknown'}`;
        } else {
          // 获取当前页面的参数
            // const pages = getCurrentPages();
            // const currentPage = pages[pages.length - 1];
            // const options = currentPage.options; // 包含url中的参数，如{id: '123'}  
            // console.log(options, currentPage, 11111111111)
            // 小程序环境
            shareUrl = `http://app.jxbylj.com/#/pages/login/wechat-authorize?userId=${userId || 'unknown'}`;
        }

        // 获取canvas上下文 - 适配H5和小程序环境
        let canvas, ctx;

        // 环境判断 - 更可靠的方式
        const isH5 = typeof document !== 'undefined' && typeof window !== 'undefined';
        
        if (isH5) {
            try {
                // 尝试直接获取DOM元素
                const domElement = document.getElementById('shareCanvas');

                // 检查是否为HTMLCanvasElement
                if (domElement && domElement instanceof HTMLCanvasElement) {
                    canvas = domElement as HTMLCanvasElement;
                    ctx = canvas.getContext('2d');
                }

                // 如果失败，创建一个临时canvas
                if (!ctx) {
                    console.warn('使用备用方式创建canvas');
                    canvas = document.createElement('canvas');
                    canvas.width = 300;
                    canvas.height = 500;
                    ctx = canvas.getContext('2d');
                }

                if (ctx) {
                    // 确保canvas尺寸设置正确
                    canvas.width = 300;
                    canvas.height = 500; // 海报高度设置为500

                    // 绘制海报
                    await drawProductSharePoster(canvas, ctx, nickname, avatar, shareUrl);
                } else {
                    console.error('获取canvas上下文失败');
                    uni.hideLoading();
                    toast.show('生成海报失败，请稍后重试');
                }
            } catch (error) {
                console.error('获取canvas元素时出错:', error);
                uni.hideLoading();
                toast.show('生成海报失败，请稍后重试');
            }
        } else {
            console.log('当前环境不是H5，尝试使用小程序API');
            // 在小程序环境中使用uni-app统一API
            try {
                // 尝试获取canvas节点，支持多种方式
                console.log('获取组件实例:', instance);
                
                try {
                    // 创建选择器查询对象
                    const query = instance ? 
                        uni.createSelectorQuery().in(instance) : 
                        uni.createSelectorQuery();
                    
                    console.log('创建selectorQuery成功');
                    
                    // 尝试多种方式查询canvas节点，提高可靠性
                    const queryMethods = [
                        // 方式1: 使用id选择器
                        () => {
                            return new Promise((resolve, reject) => {
                                query.select('#shareCanvas')
                                    .fields({ node: true, size: true })
                                    .exec((res: any) => {
                                        if (res && res[0] && res[0].node) {
                                            resolve(res[0].node);
                                        } else {
                                            reject(new Error('id选择器查询失败'));
                                        }
                                    });
                            });
                        },
                        // 方式2: 使用canvas-id选择器（小程序专用）
                        () => {
                            return new Promise((resolve, reject) => {
                                query.select('#shareCanvas')
                                    .fields({ node: true, size: true })
                                    .exec((res: any) => {
                                        if (res && res[0] && res[0].node) {
                                            resolve(res[0].node);
                                        } else {
                                            reject(new Error('canvas-id选择器查询失败'));
                                        }
                                    });
                            });
                        }
                    ];
                    
                    // 顺序尝试所有查询方式
                    let canvasNode = null;
                    for (let i = 0; i < queryMethods.length; i++) {
                        try {
                            console.log(`尝试查询方式 ${i + 1}`);
                            canvasNode = await queryMethods[i]();
                            console.log(`查询方式 ${i + 1} 成功获取canvas节点`);
                            break; // 成功获取后跳出循环
                        } catch (err) {
                            console.warn(`查询方式 ${i + 1} 失败:`, err.message);
                        }
                    }
                    
                    // 如果所有方式都失败，尝试全局选择器
                    if (!canvasNode) {
                        console.error('所有组件内查询方式均失败，尝试使用全局选择器');
                        try {
                            const globalQuery = uni.createSelectorQuery();
                            await new Promise<void>((resolve, reject) => {
                                globalQuery.select('#shareCanvas')
                                    .fields({ node: true, size: true })
                                    .exec(async (globalRes: any) => {
                                        console.log('全局查询canvas结果:', globalRes);
                                        
                                        if (!globalRes || !globalRes[0] || !globalRes[0].node) {
                                            // 尝试直接创建canvas（最后备选方案）
                                            try {
                                                console.log('尝试直接创建canvas节点');
                                                const systemInfo = wx.getSystemInfoSync();
                                                const dpr = systemInfo.pixelRatio;
                                                const tempCanvas = wx.createOffscreenCanvas({
                                                    type: '2d',
                                                    width: 300 * dpr,
                                                    height: 500 * dpr
                                                });
                                                canvasNode = tempCanvas;
                                                console.log('直接创建canvas节点成功');
                                                resolve();
                                            } catch (createError) {
                                                console.error('直接创建canvas也失败:', createError);
                                                reject(new Error('所有查询方式均失败，canvas节点不存在或无法访问'));
                                            }
                                        } else {
                                            canvasNode = globalRes[0].node;
                                            resolve();
                                        }
                                    });
                            });
                        } catch (globalError) {
                            console.error('全局查询方式也失败:', globalError);
                            uni.hideLoading();
                            toast.show('海报生成失败，请检查网络或稍后重试');
                            return;
                        }
                    }
                    
                    // 处理成功获取的canvas节点
                    if (canvasNode) {
                        await handleCanvasNode(canvasNode);
                    } else {
                        console.error('无法获取canvas节点');
                        uni.hideLoading();
                        toast.show('海报生成失败，请检查网络或稍后重试');
                    }
                    
                    // 处理canvas节点的函数
                    async function handleCanvasNode(canvasNode: any) {
                        try {
                            // 获取canvas上下文
                            const ctx = canvasNode.getContext('2d');
                            
                            if (!ctx) {
                                throw new Error('无法获取canvas绘图上下文');
                            }
                            
                            // 设置canvas尺寸（考虑设备像素比）
                            const dpr = wx.getSystemInfoSync().pixelRatio;
                            canvasNode.width = 300 * dpr;
                            canvasNode.height = 500 * dpr;
                            ctx.scale(dpr, dpr);
                            
                            // 绘制海报
                            await drawProductSharePosterInMiniProgram(canvasNode, ctx, nickname, avatar, shareUrl);
                            
                        } catch (nodeError) {
                            console.error('处理canvas节点时出错:', nodeError);
                            uni.hideLoading();
                            toast.show('海报生成失败，请稍后重试');
                        }
                    }
                    
                } catch (queryError) {
                    console.error('创建selectorQuery失败:', queryError);
                    uni.hideLoading();
                    toast.show('海报生成失败，请稍后重试');
                }
            } catch (queryError) {
                console.error('使用小程序API获取canvas失败:', queryError);
                uni.hideLoading();
                toast.show('生成海报失败，请稍后重试');
            }
        }
    } catch (error) {
        console.error('生成分享海报失败:', error);
        uni.hideLoading();
        toast.show('生成海报失败，请稍后重试');
    }
};

// 在H5环境中绘制分享海报 - 增强DOM操作健壮性
const drawProductSharePoster = async (canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D, nickname: string, avatar: string, shareUrl: string) => {
    try {
        // 绘制背景图片 - 使用白色背景
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, 300, 500);

        // 绘制上方图片区域 (375px * 340px)
        // 由于画布宽度只有300px，我们将保持比例缩放到画布宽度
        const placeholderWidth = 320; // 缩放到画布宽度
        const placeholderHeight = 340; // 保持比例
        const placeholderX = 0;
        const placeholderY = 0;
        
        // 绘制实际图片
        try {
            // 创建图片对象
            const bgImage = new Image();
            bgImage.crossOrigin = 'anonymous';
            // 设置图片路径
            bgImage.src = 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc_gen_image/8e12f819638a4a459068c8dbe978737apreview.jpeg~tplv-a9rns2rl98-image_pre_watermark_1_5.png?rcl=2025092210442619AF4D5365339AFA5D43&rk3s=8e244e95&rrcfp=ddbb2dc7&x-expires=2073869082&x-signature=%2F8MN7X8xc6HgFeBFd8xsM7rldFM%3D';
            
            // 等待图片加载完成
            await new Promise((resolve, reject) => {
                bgImage.onload = resolve;
                bgImage.onerror = () => reject(new Error('背景图片加载失败'));
                // 添加超时处理
                setTimeout(() => reject(new Error('背景图片加载超时')), 10000);
            });
            
            // 绘制图片，使其填充整个占位区域
            ctx.drawImage(bgImage, placeholderX, placeholderY, placeholderWidth, placeholderHeight);
        } catch (error) {
            console.error('加载图片失败:', error);
            // 加载失败时显示备用背景
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(placeholderX, placeholderY, placeholderWidth, placeholderHeight);
            
            // 添加加载失败提示文字
            ctx.fillStyle = '#999999';
            ctx.font = 'bold 14px sans-serif';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('图片加载失败', placeholderX + placeholderWidth/2, placeholderY + placeholderHeight/2);
        }
        
        // 添加边框
        ctx.strokeStyle = '#dddddd';
        ctx.lineWidth = 1;
        ctx.strokeRect(placeholderX, placeholderY, placeholderWidth, placeholderHeight);

        // 绘制底部信息区域
        // 头像
        const avatarX = 20;
        const avatarY = placeholderY + placeholderHeight + 60;
        const avatarSize = 60;
        
        // 绘制头像圆形背景
        ctx.fillStyle = '#f0f0f0';
        ctx.beginPath();
        ctx.arc(avatarX + avatarSize/2, avatarY + avatarSize/2, avatarSize/2, 0, Math.PI * 2);
        ctx.fill();
        
        try {
            // 尝试绘制用户头像
            const userAvatar = new Image();
            userAvatar.crossOrigin = 'anonymous';
            userAvatar.src = avatar || defaultAvatar; // 使用传入的avatar，如果没有则使用默认头像
            
            await new Promise((resolve, reject) => {
                userAvatar.onload = () => {
                    try {
                        // 保存当前状态
                        ctx.save();
                        // 创建圆形裁剪区域
                        ctx.beginPath();
                        ctx.arc(avatarX + avatarSize/2, avatarY + avatarSize/2, avatarSize/2, 0, Math.PI * 2);
                        ctx.clip();
                        // 绘制头像图片
                        ctx.drawImage(userAvatar, avatarX, avatarY, avatarSize, avatarSize);
                        // 恢复之前的状态
                        ctx.restore();
                        resolve(null);
                    } catch (drawError) {
                        reject(drawError);
                    }
                };
                userAvatar.onerror = () => reject(new Error('头像图片加载失败'));
                // 添加超时处理
                setTimeout(() => reject(new Error('头像图片加载超时')), 10000);
            });
        } catch (error) {
            console.error('加载用户头像失败:', error);
            // 如果头像加载失败，显示默认图标
            ctx.font = '30px sans-serif';
            ctx.fillStyle = '#999999';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('👤', avatarX + avatarSize/2, avatarY + avatarSize/2);
        }
        
        // 绘制昵称
        ctx.font = '14px sans-serif';
        ctx.fillStyle = '#333333';
        ctx.textAlign = 'left';
        ctx.textBaseline = 'top';
        ctx.fillText(`[${nickname}]`, avatarX + avatarSize + 12, avatarY + 8);
        
        // 绘制推荐文字
        ctx.font = '12px sans-serif';
        ctx.fillStyle = '#666666';
        ctx.fillText('推荐您加入李氏家庭', avatarX + avatarSize + 12, avatarY + 50);

        // 二维码定位数据
        const qrCodeX = 210;
        const qrCodeY = placeholderY + placeholderHeight + 50;
        const qrCodeSize = 80;

        // 生成并绘制二维码
        try {
            const qrCodeUrl = await generateQRCode(shareUrl);
            const qrImg = new Image();
            qrImg.crossOrigin = 'anonymous';
            qrImg.src = qrCodeUrl;

            await new Promise((resolve, reject) => {
                qrImg.onload = resolve;
                qrImg.onerror = () => reject(new Error('二维码图片加载失败'));
                // 添加超时处理
                setTimeout(() => reject(new Error('二维码图片加载超时')), 10000);
            });

            // 绘制二维码
            ctx.drawImage(qrImg, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
        } catch (qrError) {
            console.error('二维码生成或绘制失败:', qrError);
            // 显示二维码区域占位
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
            ctx.strokeStyle = '#dddddd';
            ctx.lineWidth = 1;
            ctx.strokeRect(qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
            
            // 添加提示文字
            ctx.fillStyle = '#999999';
            ctx.font = '10px sans-serif';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('扫码加入', qrCodeX + qrCodeSize/2, qrCodeY + qrCodeSize/2);
        }

        // 隐藏加载提示
        uni.hideLoading();

        // 显示图片预览 - 增强DOM操作健壮性
        try {
            const imageUrl = canvas.toDataURL('image/png');

            // 检查document和body是否存在
            if (typeof document === 'undefined' || !document.body) {
                console.error('DOM环境不可用，无法显示预览');
                toast.show('海报已生成，请刷新页面后重试');
                return;
            }

            // 创建预览弹窗
            const modal = document.createElement('div');
            modal.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.7);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      z-index: 9999;
    `;

            const previewImage = document.createElement('img');
            previewImage.src = imageUrl;
            previewImage.style.cssText = `
      max-height: 82vh;
      margin-bottom: 20px;
    `;

            const saveBtn = document.createElement('button');
            saveBtn.innerText = '保存图片';
            saveBtn.style.cssText = `
      padding: 10px 30px;
      background-color: #3b8dff;
      color: white;
      border: none;
      border-radius: 4px;
      font-size: 16px;
      cursor: pointer;
    `;

            saveBtn.onclick = () => {
                try {
                    const link = document.createElement('a');
                    link.href = imageUrl;
                    link.download = '数字家谱分享.png';
                    // 对于某些浏览器，需要添加到DOM并模拟点击
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    toast.show('保存成功');
                } catch (saveError) {
                    console.error('保存图片失败:', saveError);
                    toast.show('保存失败，请手动截图保存');
                }
            };

            const closeBtn = document.createElement('div');
            closeBtn.innerText = '✕';
            closeBtn.style.cssText = `
      position: absolute;
      top: 10px;
      right: 10px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.8);
      color: #333;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      cursor: pointer;
      z-index: 10000;
    `;

            // 添加键盘事件监听
            const handleKeydown = (e: KeyboardEvent) => {
                if (e.key === 'Escape') {
                    closeModal();
                }
            };

            // 添加点击外部关闭
            const handleClickOutside = (e: MouseEvent) => {
                if (e.target === modal) {
                    closeModal();
                }
            };

            // 关闭模态框的函数
            const closeModal = () => {
                if (document.body.contains(modal)) {
                    document.body.removeChild(modal);
                }
                // 移除事件监听
                document.removeEventListener('keydown', handleKeydown);
                modal.removeEventListener('click', handleClickOutside);
            };

            closeBtn.onclick = closeModal;
            document.addEventListener('keydown', handleKeydown);
            modal.addEventListener('click', handleClickOutside);

            modal.appendChild(previewImage);
            modal.appendChild(saveBtn);
            modal.appendChild(closeBtn);
            document.body.appendChild(modal);
        } catch (modalError) {
            console.error('创建预览弹窗失败:', modalError);
            toast.show('海报已生成，请刷新页面后重试');
        }

    } catch (error) {
        console.error('绘制海报失败:', error);
        uni.hideLoading();
        toast.show('生成海报失败，请稍后重试');
    }
};

// 在小程序环境中绘制分享海报
const drawProductSharePosterInMiniProgram = async (canvas: any, ctx: CanvasRenderingContext2D, nickname: string, avatar: string, shareUrl: string) => {
    try {
        // 绘制背景图片
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, 320, 540);
        
        // 绘制上方区域 - 不再显示商品内容
        const headerX = 0;
        const headerY = 0;
        const headerWidth = 320;
        const headerHeight = 340;
        
        // 绘制主题图片
        try {
            const headerImage = canvas.createImage();
            headerImage.src = 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc_gen_image/8e12f819638a4a459068c8dbe978737apreview.jpeg~tplv-a9rns2rl98-image_pre_watermark_1_5.png?rcl=2025092210442619AF4D5365339AFA5D43&rk3s=8e244e95&rrcfp=ddbb2dc7&x-expires=2073869082&x-signature=%2F8MN7X8xc6HgFeBFd8xsM7rldFM%3D';
            
            // 添加加载超时处理
            await new Promise((resolve, reject) => {
                headerImage.onload = resolve;
                headerImage.onerror = () => reject(new Error('图片加载失败'));
                // 设置10秒超时
                setTimeout(() => reject(new Error('图片加载超时')), 10000);
            });
            
            // 绘制图片
            ctx.drawImage(headerImage, headerX, headerY, headerWidth, headerHeight);
        } catch (imageError) {
            console.error('图片加载失败:', imageError);
            
            // 加载失败时显示灰色背景和提示文字
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(headerX, headerY, headerWidth, headerHeight);
            
            // 绘制边框
            ctx.strokeStyle = '#dddddd';
            ctx.lineWidth = 1;
            ctx.strokeRect(headerX, headerY, headerWidth, headerHeight);
            
            // 绘制加载失败文字提示
            ctx.font = '14px sans-serif';
            ctx.fillStyle = '#999999';
            ctx.textAlign = 'center';
            ctx.fillText('图片加载失败', headerWidth / 2, headerY + headerHeight / 2);
            ctx.textAlign = 'left'; // 恢复默认对齐方式
        }

        // 底部信息区域 - 根据H5布局添加
        // 头像
        const avatarX = 20;
        const avatarY = headerY + headerHeight + 60;
        const avatarSize = 60;
        
        // 绘制头像圆形背景
        ctx.fillStyle = '#f0f0f0';
        ctx.beginPath();
        ctx.arc(avatarX + avatarSize/2, avatarY + avatarSize/2, avatarSize/2, 0, Math.PI * 2);
        ctx.fill();
        
        try {
            // 尝试绘制用户头像
            const userAvatar = canvas.createImage();
            userAvatar.src = avatar || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250926/aab14ee17a5240fca6afb57789e74445.png'; // 使用传入的avatar，如果没有则使用默认头像
            
            await new Promise((resolve, reject) => {
                userAvatar.onload = () => {
                    try {
                        // 保存当前状态
                        ctx.save();
                        // 创建圆形裁剪区域
                        ctx.beginPath();
                        ctx.arc(avatarX + avatarSize/2, avatarY + avatarSize/2, avatarSize/2, 0, Math.PI * 2);
                        ctx.clip();
                        // 绘制头像图片
                        ctx.drawImage(userAvatar, avatarX, avatarY, avatarSize, avatarSize);
                        // 恢复之前的状态
                        ctx.restore();
                        resolve(null);
                    } catch (drawError) {
                        reject(drawError);
                    }
                };
                userAvatar.onerror = () => reject(new Error('头像图片加载失败'));
                // 添加超时处理
                setTimeout(() => reject(new Error('头像图片加载超时')), 10000);
            });
        } catch (error) {
            console.error('加载用户头像失败:', error);
            // 如果头像加载失败，显示默认图标
            ctx.font = '30px sans-serif';
            ctx.fillStyle = '#999999';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('👤', avatarX + avatarSize/2, avatarY + avatarSize/2);
            ctx.textAlign = 'left'; // 恢复默认对齐方式
        }
        
        // 绘制昵称
        ctx.font = '14px sans-serif';
        ctx.fillStyle = '#333333';
        ctx.textAlign = 'left';
        ctx.textBaseline = 'top';
        ctx.fillText(`[${nickname}]`, avatarX + avatarSize + 12, avatarY + 8);
        
        // 绘制推荐文字
        ctx.font = '12px sans-serif';
        ctx.fillStyle = '#666666';
        ctx.fillText('推荐您加入李氏家庭', avatarX + avatarSize + 12, avatarY + 50);
        
        // 绘制分享者信息（保留）
        ctx.font = '14px sans-serif';
        ctx.fillStyle = '#666666';
        ctx.fillText(`分享自: ${nickname}`, 20, avatarY + 100);

    // 二维码定位数据
    const qrCodeX = 210;
    const qrCodeY = headerY + headerHeight + 50;
    const qrCodeSize = 80;

    // 生成并绘制二维码
    try {
      const qrCodeUrl = await generateQRCode(shareUrl);
      const qrImg = canvas.createImage();
      qrImg.src = qrCodeUrl;

      // 添加超时处理
      await new Promise((resolve, reject) => {
        qrImg.onload = resolve;
        qrImg.onerror = () => reject(new Error('二维码图片加载失败'));
        setTimeout(() => reject(new Error('二维码图片加载超时')), 10000);
      });

      // 绘制二维码
      ctx.drawImage(qrImg, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
    } catch (qrError) {
      console.error('二维码生成或绘制失败:', qrError);
      // 显示二维码区域占位
      ctx.fillStyle = '#f0f0f0';
      ctx.fillRect(qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
      ctx.strokeStyle = '#dddddd';
      ctx.lineWidth = 1;
      ctx.strokeRect(qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
      
      // 添加提示文字
      ctx.fillStyle = '#999999';
      ctx.font = '10px sans-serif';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('扫码加入', qrCodeX + qrCodeSize/2, qrCodeY + qrCodeSize/2);
      ctx.textAlign = 'left'; // 恢复默认对齐方式
    }

    // 将canvas转换为图片并预览 - 适配小程序环境
    try {
      const isMiniProgram = typeof wx !== 'undefined' && typeof wx.getSystemInfoSync === 'function';
      
      // 构建canvasToTempFilePath参数，根据环境选择合适的参数
      const canvasToTempFilePathParams: any = {};
      
      if (isMiniProgram) {
        // 小程序环境：优先使用canvas参数，这是更现代的方式
        if (canvas) {
          canvasToTempFilePathParams.canvas = canvas;
        } else {
          // 如果没有canvas对象，回退到使用canvasId
          canvasToTempFilePathParams.canvasId = 'shareCanvas';
        }
      } else {
        // 其他环境：同时使用canvasId和canvas参数以提高兼容性
        canvasToTempFilePathParams.canvasId = 'shareCanvas';
        if (canvas) {
          canvasToTempFilePathParams.canvas = canvas;
        }
      }
      
      // 添加必要的success和fail回调
      canvasToTempFilePathParams.success = (res: any) => {
        // 隐藏加载提示
        uni.hideLoading();

        // 显示图片预览，用户可自行长按保存
        uni.previewImage({
          urls: [res.tempFilePath],
          current: res.tempFilePath,
          success: () => {
            console.log('图片预览成功');
          },
          fail: (err: any) => {
            console.error('预览图片失败:', err);
            toast.show('海报已生成，您可以在相册中查看');
          }
        });
      };
      
      canvasToTempFilePathParams.fail = (err: any) => {
        console.error('生成图片失败:', err);
        // 尝试降级方案：如果是因为canvas参数问题，尝试只使用canvasId
        if (isMiniProgram && canvas) {
          console.warn('尝试使用canvasId作为降级方案');
          uni.canvasToTempFilePath({
            canvasId: 'shareCanvas',
            success: (res: any) => {
              uni.hideLoading();
              uni.previewImage({
                urls: [res.tempFilePath],
                current: res.tempFilePath
              });
            },
            fail: (fallbackErr: any) => {
              console.error('降级方案也失败:', fallbackErr);
              uni.hideLoading();
              toast.show('海报生成失败，请稍后重试');
            }
          });
        } else {
          uni.hideLoading();
          toast.show('海报生成失败，请稍后重试');
        }
      };
      
      // 执行canvasToTempFilePath调用
      uni.canvasToTempFilePath(canvasToTempFilePathParams);
    } catch (convertError) {
      console.error('canvasToTempFilePath调用异常:', convertError);
      uni.hideLoading();
      toast.show('海报生成失败，请稍后重试');
    }
  } catch (error) {
    console.error('绘制海报失败:', error);
    throw error;
  }
};

// 生成二维码图片 - 增强小程序环境兼容性
const generateQRCode = async (url: string): Promise<string> => {
    try {
        // 环境判断
        const isH5 = typeof document !== 'undefined' && typeof window !== 'undefined';
        const isMiniProgram = typeof wx !== 'undefined' && typeof wx.getSystemInfoSync === 'function';
        
        if (isH5) {
            // H5环境：生成base64格式的二维码
            try {
                const canvas = document.createElement('canvas');
                await QRCode.toCanvas(canvas, url, {
                    width: 120,
                    margin: 1,
                    color: {
                        dark: '#333333',
                        light: '#ffffff'
                    }
                });
                return canvas.toDataURL('image/png');
            } catch (canvasError) {
                console.warn('Canvas生成二维码失败，使用降级方案:', canvasError);
                // 降级方案：使用外部API
                return `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(url)}`;
            }
        } else if (isMiniProgram) {
            // 小程序环境：使用更可靠的方式处理二维码
            try {
                // 对于小程序环境，确保URL是有效的，不包含不支持的协议
                let processedUrl = url;
                
                // 如果URL不以pages/开头且没有协议前缀，添加默认页面路径
                if (!processedUrl.startsWith('pages/') && !processedUrl.startsWith('http://') && !processedUrl.startsWith('https://')) {
                    processedUrl = `pages/${processedUrl}`;
                }
                
                // 生成带参数的二维码图片链接，添加缓存控制参数避免缓存问题
                const timestamp = Date.now();
                return `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(processedUrl)}&_=${timestamp}`;
            } catch (miniError) {
                console.error('小程序环境二维码生成失败:', miniError);
                // 降级方案：使用外部API，添加错误重试参数
                const timestamp = Date.now();
                return `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(url)}&_=${timestamp}`;
            }
        } else {
            // 其他环境：使用外部API生成二维码
            const timestamp = Date.now();
            return `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(url)}&_=${timestamp}`;
        }
    } catch (error) {
        console.error('生成二维码失败:', error);
        // 降级方案：使用外部API，确保返回有效的URL
        const timestamp = Date.now();
        return `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(url || 'default-url')}&_=${timestamp}`;
    }
};

// 文本换行处理函数 - 增强兼容性和可靠性
const wrapText = (ctx: CanvasRenderingContext2D, text: string, maxWidth: number, fontSize: number, lineHeight: number = fontSize + 4, maxLines: number = 10) => {
    // 参数验证和防御性编程
    if (!ctx || typeof text !== 'string' || maxWidth <= 0 || fontSize <= 0) {
        return text ? [text] : [];
    }

    // 临时保存当前字体设置
    const originalFont = ctx.font;
    
    // 设置字体大小
    try {
        ctx.font = `${fontSize}px sans-serif`;
    } catch (e) {
        console.warn('字体设置失败，使用默认字体:', e);
    }

    const lines: string[] = [];
    let remainingText = text.trim();

    // 优先按空格分割，保持英文单词完整
    while (remainingText.length > 0 && lines.length < maxLines) {
        // 尝试找到合适的换行位置
        let lineBreakIndex = -1;
        let bestFitWidth = 0;
        
        // 先尝试找到不超过最大宽度的最长单词组合
        const words = remainingText.split(' ');
        let tempLine = '';
        
        for (let i = 0; i < words.length; i++) {
            const testLine = tempLine + (tempLine ? ' ' : '') + words[i];
            const testWidth = ctx.measureText(testLine).width;
            
            if (testWidth <= maxWidth) {
                tempLine = testLine;
                bestFitWidth = testWidth;
                lineBreakIndex = i;
            } else {
                // 如果是第一个单词就超过宽度，需要按字符分割
                if (i === 0) {
                    tempLine = '';
                    for (let j = 0; j < words[0].length; j++) {
                        const charTestLine = tempLine + words[0][j];
                        const charTestWidth = ctx.measureText(charTestLine).width;
                        
                        if (charTestWidth <= maxWidth) {
                            tempLine = charTestLine;
                            bestFitWidth = charTestWidth;
                        } else {
                            if (j > 0) {
                                lineBreakIndex = 0;
                                remainingText = words[0].substring(j) + ' ' + remainingText.substring(words[0].length);
                            }
                            break;
                        }
                    }
                    break;
                } else {
                    break;
                }
            }
        }
        
        // 如果找到了合适的换行位置
        if (tempLine.length > 0) {
            lines.push(tempLine);
            
            // 更新剩余文本
            if (lineBreakIndex >= 0 && words.length > 0) {
                if (lineBreakIndex < words.length - 1) {
                    remainingText = words.slice(lineBreakIndex + 1).join(' ');
                } else if (lineBreakIndex === 0 && remainingText.length > tempLine.length) {
                    // 处理按字符分割的情况
                    // remainingText已经在前面更新了
                } else {
                    remainingText = '';
                }
            } else {
                remainingText = '';
            }
            
            remainingText = remainingText.trim();
        } else {
            // 如果无法找到合适的换行位置，添加整个剩余文本
            lines.push(remainingText);
            break;
        }
        
        // 如果剩余文本已经处理完，跳出循环
        if (!remainingText) {
            break;
        }
    }
    
    // 如果文本超出了最大行数限制，添加省略号
    if (remainingText.length > 0 && lines.length >= maxLines) {
        // 尝试在最后一行添加省略号
        let lastLine = lines[lines.length - 1];
        while (true) {
            const ellipsisLine = lastLine.slice(0, -1) + '...';
            const ellipsisWidth = ctx.measureText(ellipsisLine).width;
            
            if (ellipsisWidth <= maxWidth || lastLine.length <= 1) {
                lines[lines.length - 1] = ellipsisLine;
                break;
            }
            
            lastLine = lastLine.slice(0, -1);
        }
    }

    // 恢复原始字体设置
    try {
        ctx.font = originalFont;
    } catch (e) {
        console.warn('恢复字体设置失败:', e);
    }

    return lines;
};


defineExpose({
    createProductSharePoster
})
</script>

<style lang="scss" scoped>
.mine-container {
    padding-bottom: 100rpx;
    background-color: #f5f7fa;
}

// 用户信息卡片
.user-profile {
    position: relative;
    padding: 30rpx;
    overflow: hidden;

    .blur-bg {
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        z-index: 0;
        height: 240rpx;
        background: linear-gradient(to bottom, var(--primary-color), var(--primary-color-light));
    }

    .user-info {
        position: relative;
        z-index: 1;
        display: flex;
        align-items: center;

        .avatar-container {
            position: relative;

            .avatar {
                width: 120rpx;
                height: 120rpx;
                border: 4rpx solid rgba(255, 255, 255, 0.8);
                border-radius: 50%;
                box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
            }
        }

        .user-details {
            flex: 1;
            margin-left: 24rpx;

            .nickname {
                margin-bottom: 8rpx;
                font-size: 34rpx;
                font-weight: bold;
                color: #fff;
            }

            .user-id {
                font-size: 24rpx;
                color: rgba(255, 255, 255, 0.8);
            }
        }
    }
}

// 卡片容器通用样式
.card-container {
    margin: 24rpx 30rpx;
    overflow: hidden;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.04);

    .card-header {
        display: flex;
        align-items: center;
        padding: 20rpx 24rpx;
        border-bottom: 1rpx solid #f5f5f5;

        .card-title {
            display: flex;
            align-items: center;

            text {
                margin-left: 12rpx;
                font-size: 28rpx;
                font-weight: 600;
                color: #333;
            }
        }
    }

    .share-section {
        padding: 30rpx;
        text-align: center;
    }

    .share-btn {
        width: 100%;
    }
}
</style>